const EventUtil = require('./util/EventUtil');
const ConstantValues = require('./event/ConstantValues');
const https = require('https');

const eventUtil = new EventUtil();

const eventObserver = {};

eventUtil.on(ConstantValues.httpResp, (data) => {
    const { tag, result } = data;
    const callback = eventObserver[tag];
    if (typeof callback === 'function') {
        callback(result);
    }
    // console.log('http response, data ', data);
});

const registerObserver = (tag, callback) => {
    eventObserver[tag] = callback;
};

const httpGetUrl = (url, path, body) => {
    const getUrl = url + path;
    let bodyStr = '';
    const keys = Object.keys(body);
    const { length } = keys;
    keys.forEach((k, index) => {
        if (index < length - 1) {
            bodyStr += k+'='+body[k]+'&';
        } else {
            bodyStr += k+'='+body[k];
        }

    });
    return getUrl+'?'+bodyStr;
};

const invokeHttpCallback = (callback) => (res) => {
    if (res.statusCode !== 200) {
        console.log(`STATUS: ${res.statusCode}`);
    }
    // console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    const chunks = [];
    res.on('data', (chunk) => {
        // console.log('on data ');
        chunks.push(chunk);
    });
    res.on('end', () => {
        const body = Buffer.concat(chunks);
        const str = body.toString();
        callback(str);
    });
    res.on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
    });
};

const httpsGet = (url, tag) => {
    const req = https.get(url, (res) => {
        const chunks = [];
        res.on('data', (chunk) => {
            // console.log('on data ');
            chunks.push(chunk);
        });
        res.on('end', () => {
            const body = Buffer.concat(chunks);
            const str = body.toString();
            eventUtil.emit(ConstantValues.httpResp, { tag, result: str });
        });
        res.on('error', (e) => {
            console.error(`problem with request: url: ${url}, ${e.message}`);
        });
    });
    req.on('abort', (res) => {
        console.error(`on request abort : url: ${url}, ${res.statusCode}`);
    });
    req.on('timeout', (res) => {
        console.error(`on request timeout : url: ${url}, ${res.statusCode}`);
    });
    req.end();
};

module.exports = {
    httpGetUrl,
    invokeHttpCallback,
    httpsGet,
    registerObserver,
};
